package com.zhitan.ems.alarm.controller;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zhitan.ems.alarm.entity.AlarmRulesEntity;
import com.zhitan.ems.alarm.service.AlarmRulesService;
import com.zhitan.ems.alarm.vo.AlarmRulesVO;
import com.zhitan.ems.alarm.wrapper.AlarmRulesWrapper;
import com.zhitan.ems.app.iot.entity.DeviceEntity;
import com.zhitan.ems.app.iot.entity.DevicePropertyEntity;
import com.zhitan.ems.app.iot.entity.GroupEntity;
import com.zhitan.ems.app.iot.service.DevicePropertyService;
import com.zhitan.ems.app.iot.service.DeviceService;
import com.zhitan.ems.app.iot.service.GroupService;
import com.zhitan.ems.common.annotation.Log;
import com.zhitan.ems.common.core.controller.BaseController;
import com.zhitan.ems.common.core.domain.R;
import com.zhitan.ems.common.enums.BusinessType;
import com.zhitan.ems.common.utils.DateUtils;
import com.zhitan.ems.common.utils.StringUtils;
import com.zhitan.ems.common.utils.poi.ExcelUtil;
import com.zhitan.ems.framework.core.vo.VPage;
import com.zhitan.ems.framework.core.vo.VQueryKit;

import cn.hutool.core.util.IdUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
/**
 * 报警规则配置表
 * @author zhitan
 * 
 * @date 2025-09-26 21:25:31
 */
@Api(tags = "报警规则配置表", value = "报警规则配置表")
@RestController
@RequestMapping("intra/alarm/alarmrules")
public class AlarmRulesController extends BaseController{
    @Autowired
    private AlarmRulesService alarmRulesService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private DevicePropertyService devicePropertyService;
    @Autowired
	private GroupService groupService;
    /**
     * 列表
     */
    @ApiOperation(value = "列表", response = VPage.class)
    @ApiImplicitParams({
		        @ApiImplicitParam(name = "name", value = "标题",  paramType = "query", required = false, dataType =  "String"),
		})
    @GetMapping("/browse")
    @PreAuthorize("@ss.hasPermi('alarm:alarmrules:list')")
    public R<VPage<AlarmRulesVO>> browse(@RequestParam Map<String, Object> params){
        QueryWrapper<AlarmRulesEntity> queryWrapper=VQueryKit.getQueryWrapperByMap(params,Arrays.asList("name"), AlarmRulesEntity.class);
        queryWrapper.orderByDesc("rule_id");
         queryWrapper.like(StringUtils.isNotNull(params.get("name")),"name", params.get("name"));
        IPage<AlarmRulesEntity> pages = alarmRulesService.page(VQueryKit.getPage(params), queryWrapper);
        return R.data(AlarmRulesWrapper.build().toVPageVO(pages));
    }
    @GetMapping("/listStat")
    @PreAuthorize("@ss.hasPermi('alarm:alarmrules:list')")
    public R<Map<String, Object>> listStat(@RequestParam Map<String, Object> params)throws ParseException{
         QueryWrapper<AlarmRulesEntity> queryWrapper=VQueryKit.getQueryWrapperByMap(params,Arrays.asList("name"), AlarmRulesEntity.class);
         queryWrapper.select("count(rule_id) as total,sum(id) as all");
         queryWrapper.like(StringUtils.isNotNull(params.get("name")),"name", params.get("name"));
        if(params.containsKey("createDate")) {
            queryWrapper.between("create_at",
                    DateUtils.getStartOfDate(DateUtils.str_ToDate(params.get("createDate").toString())),
                    DateUtils.getEndOfDate(DateUtils.str_ToDate(params.get("createDate").toString()))
              );   
        }
        Map<String, Object>  stat=alarmRulesService.getMap(queryWrapper);
        return R.data(stat);
    }
    @ApiOperation("导出")
	@Log(title = "参数管理", businessType = BusinessType.EXPORT)
	@PreAuthorize("@ss.hasPermi('alarm:alarmrules:list')")
	@PostMapping("/toExport")
	public void toExport(HttpServletResponse response, @RequestParam Map<String, Object> params) {
		QueryWrapper<AlarmRulesEntity> queryWrapper = VQueryKit.getQueryWrapperByMap(params, Arrays.asList("name"),
				AlarmRulesEntity.class);
		queryWrapper.orderByDesc("rule_id");
		queryWrapper.like(StringUtils.isNotNull(params.get("name")), "name", params.get("name"));
		 List<AlarmRulesEntity> alarmRulesList = alarmRulesService.list(queryWrapper);
		ExcelUtil<AlarmRulesEntity> util = new ExcelUtil<>(AlarmRulesEntity.class);
		util.exportExcel(response, alarmRulesList, "参数数据");
	}
   
    /**
     * 信息
     */
    @ApiOperation(value = "信息", response = AlarmRulesVO.class)
    @GetMapping("/detail/{ruleId}")
    @PreAuthorize("@ss.hasPermi('alarm:alarmrules:info')")
    public R<AlarmRulesVO> detail(@PathVariable("ruleId") String ruleId){
		AlarmRulesEntity alarmRules = alarmRulesService.getById(ruleId);
	    return R.data(AlarmRulesWrapper.build().entityVO(alarmRules));
    }
     /**
     * 保存&更新 
     */
    @Log(title = "报警规则配置表", businessType = BusinessType.ADDANDEDIT)
    @ApiOperation(value = "保存&更新", response = Boolean.class)
    @PostMapping("/submit")
    @PreAuthorize("@ss.hasPermi('alarm:alarmrules:save')")
    public R<AlarmRulesVO> submit(@Valid @RequestBody AlarmRulesVO alarmRules){
    	 if(alarmRules.getRuleId()==null) {
           return add(alarmRules);
         }else {
           return edit(alarmRules);
        }
    }
    
    @Log(title = "报警规则配置表", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增", response = Boolean.class)
    @PostMapping("/add")
    @PreAuthorize("@ss.hasPermi('alarm:alarmrules:save')")
    public R<AlarmRulesVO> add(@Valid @RequestBody AlarmRulesVO alarmRules){
   		if(alarmRules.getRuleId()==null) {
   			alarmRules.setRuleId(IdUtil.fastSimpleUUID());
            alarmRules.setCreateAt(new Date());
            alarmRules.setIsDelete(0);
            alarmRules.setUpdateAt(new Date());
        }
   		if(alarmRules.getDeviceId()!=null) {
   			DeviceEntity device=deviceService.getById(alarmRules.getDeviceId());
   			if(device!=null) {
   				alarmRules.setDeviceCode(device.getDeviceCode());
   				alarmRules.setDeviceName(device.getDeviceCode());
   			}
   		}
   		if(alarmRules.getGroupId()!=null) {
   			GroupEntity group=groupService.getById(alarmRules.getGroupId());
   			if(group!=null) {
   				alarmRules.setGroupName(group.getGroupName());
   			}
   		}
   		if(alarmRules.getDataPropertyId()!=null) {
   			DevicePropertyEntity deviceProperty=devicePropertyService.getById(alarmRules.getDataPropertyId());
   			if(deviceProperty!=null) {
   				alarmRules.setDataCode(deviceProperty.getDataCode());
   				alarmRules.setDataFormCode(deviceProperty.getDataFormCode());
   			}
   		}
    	if(alarmRulesService.save(alarmRules)) {
    		 return R.ok(alarmRules);
    	 }
    	return R.error("数据错误");
    }
    
    @Log(title = "报警规则配置表", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "更新", response = Boolean.class)
    @PostMapping("/edit")
    @PreAuthorize("@ss.hasPermi('alarm:alarmrules:update')")
    public R<AlarmRulesVO> edit(@Valid @RequestBody AlarmRulesVO alarmRules){
   		alarmRules.setUpdateAt(new Date());
   		if(alarmRules.getDeviceId()!=null) {
   			DeviceEntity device=deviceService.getById(alarmRules.getDeviceId());
   			if(device!=null) {
   				alarmRules.setDeviceCode(device.getDeviceCode());
   				alarmRules.setDeviceName(device.getDeviceCode());
   			}
   		}
   		if(alarmRules.getGroupId()!=null) {
   			GroupEntity group=groupService.getById(alarmRules.getGroupId());
   			if(group!=null) {
   				alarmRules.setGroupName(group.getGroupName());
   			}
   		}
   		if(alarmRules.getDataPropertyId()!=null) {
   			DevicePropertyEntity deviceProperty=devicePropertyService.getById(alarmRules.getDataPropertyId());
   			if(deviceProperty!=null) {
   				alarmRules.setDataCode(deviceProperty.getDataCode());
   				alarmRules.setDataFormCode(deviceProperty.getDataFormCode());
   			}
   		}
    	if(alarmRulesService.updateById(alarmRules)) {
    		 return R.ok(alarmRules);
    	 }
    	return R.error("数据错误");
    }
    /**
     * 删除
     */
    @ApiOperation(value = "删除", response = Boolean.class)
    @DeleteMapping("/delete")
    @PreAuthorize("@ss.hasPermi('alarm:alarmrules:delete')")
    @Log(title = "报警规则配置表", businessType = BusinessType.DELETE)
    public R<Boolean> delete(@RequestBody String[] ruleIds){
        return R.ok(alarmRulesService.removeByIds(Arrays.asList(ruleIds)));
    }
    public static void main(String[] args) {
    	System.out.println(IdUtil.fastSimpleUUID().length());
	}

}
